# routers/card.py
# 卡牌相关接口：上传、查询、出售
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from schemas import CardCreate, CardOut, UserCardOut
from models import Card, UserCard, User
from crud import get_card_by_code, create_card, add_user_card
from deps import get_db
from typing import List

router = APIRouter(prefix="/card", tags=["卡牌"])

@router.post("/add", response_model=CardOut)
def add_card(card: CardCreate, db: Session = Depends(get_db)):
    """添加新卡牌（仅管理员或初始化用）"""
    if get_card_by_code(db, card.code):
        raise HTTPException(status_code=400, detail="卡牌编号已存在")
    return create_card(db, card)

@router.get("/list", response_model=List[CardOut])
def list_cards(skip: int = 0, limit: int = 20, db: Session = Depends(get_db)):
    """查询所有卡牌"""
    return db.query(Card).offset(skip).limit(limit).all()

@router.post("/sell", response_model=UserCardOut)
def sell_card(user_id: int, card_code: str, quantity: int, price: float, db: Session = Depends(get_db)):
    """用户上传自己拥有的卡牌进行出售"""
    card = get_card_by_code(db, card_code)
    if not card:
        raise HTTPException(status_code=404, detail="卡牌不存在")
    return add_user_card(db, user_id, card.id, quantity, price)

@router.get("/search", response_model=List[CardOut])
def search_cards(code: str = "", name: str = "", rarity: str = "", type: str = "", db: Session = Depends(get_db)):
    """多条件搜索卡牌"""
    query = db.query(Card)
    if code:
        query = query.filter(Card.code == code)
    if name:
        query = query.filter(Card.name.contains(name))
    if rarity:
        query = query.filter(Card.rarity == rarity)
    if type:
        query = query.filter(Card.type == type)
    return query.all() 